<?php

header("content-type:text/html;charset=utf8");
date_default_timezone_set('PRC');
// $serverName = "localhost";
// $userName = "root";
// $pwd = "root";
// $dbName = "materialadmin ";
//如果连接上数据库后，改变了数据库的结构，会造成下次连接的时候数据库连接不上，解决方法就是重启服务器
$conn = new mysqli('localhost', 'root', 'root', 'materialadmin');

//保证查询出来的中文不会出现乱码
mysqli_set_charset($conn, "utf8");

if ($conn->connect_error) {
    die("连接失败：" . $conn->connect_error);
};


include "./inc.setToken.php";

// 接收管理员和密码
$username = $_GET["usersname"];
$pass = $_GET["pass"];

//管理员是否存在
$sql = "select * from login";
// where username='{$username}'
$result = $conn->query($sql);
// print_r( $result);
//如果管理员存在
if ($result->num_rows > 0) {
    $row = mysqli_fetch_assoc($result);
    // print_r( $row );

    if ($pass == $row["pass"]) {
        //密码正确
        //生成Token和过期日期
        $token = setToken();
        //7天过期
        $time_out = strtotime("+7 days");

        $sql2 = "update login set token='{$token}',time_out='{$time_out}' where username='{$username}'";

        if ($conn->query($sql2) === TRUE) {
            // 登录成功
            $data['code'] = 3000;
            $data["token"] = $token;
            $data["msg"] = '登录成功';
            $data["time_out"] = $time_out;
        } else {
            //服务器错误
            $data['code'] = 3001;
            $data["msg"] = '未知错误';
        }
    } else {
        //密码错误
        $data['code'] = 3003;
        $data["msg"] = '密码错误';
    }
} else {
    // 用户名不存在
    $data['code'] = 3002;
    $data["msg"] = '用户不存在';
}
echo json_encode($data);
